import json
import os
from django.http import HttpResponse, JsonResponse
from django.utils import timezone
from Moment.models import Moment
def uploadFiles(request):
    time = str(timezone.now())
    nameList = []
    for filename, file in request.FILES.items():

        fname=time + "_" + filename

        fname = fname.replace(" ", "")
        fname = fname.replace(":", "")
        fname = fname.replace("-", "")
        fname = fname.replace("+", "")
        fname = fname.replace("_", "")

        destination = open(os.path.join("files/moment", fname), "wb+")
        for chunk in file.chunks():
            destination.write(chunk)
        destination.close()
        nameList.append("files/moment/"+fname)
    Moment.objects.create(
        content=request.GET.get("content"),
        files=json.dumps(nameList),
        account=request.GET.get("account")
    ).save()
    return HttpResponse("上传完成")

def query(request):
    if request.method == 'GET':
        moment = Moment.objects.all()
        return JsonResponse({"data":[{
            "content":each.content,
            "files":each.files,
            "createTime":each.createTime,
            "account":each.account,
            "id":each.id,
        }for each in moment.order_by('-createTime')]})
    else:
        return HttpResponse("请使用GET")
def queryPerson(request):
    if request.method == 'GET':
        moment = Moment.objects.filter(account=request.GET.get("account"))
        return JsonResponse({"data":[{
            "content":each.content,
            "files":each.files,
            "createTime":each.createTime,
            "account":each.account,
            "id":each.id,
        }for each in moment.order_by('-createTime')]})
    else:
        return HttpResponse("请使用GET")

def delete(request):
    if request.method == 'GET':
        m=Moment.objects.filter(id=request.GET.get("id"))
        for a in json.loads(m[0].files):
            os.remove(a)
        m.delete()
        return HttpResponse("删除成功")
    else:
        return HttpResponse("请使用GET")

